package controller;

import java.io.IOException;
import java.util.ArrayList;

import DAO.DietDAO;
import DAO.MenuDAO;
import DTO.DietDTO;
import DTO.MenuDTO;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class MenuGroupServlet
 */
public class MenuServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MenuServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession().getAttribute("ADMIN_USERNAME") != null) {
			response.setContentType("UTF-8");
			DietDAO dietDAO = new DietDAO();
			ArrayList<DietDTO> dietlist = dietDAO.select();
			request.setAttribute("DIETLIST", dietlist);

			MenuDAO menuDao = new MenuDAO();
			ArrayList<MenuDTO> menuList = menuDao.select();
			for (MenuDTO menu : menuList) {
				DietDTO diet = menu.getDiet();
				dietDAO.get(diet);
			}

			request.setAttribute("MENULIST", menuList);
			RequestDispatcher rd = request
					.getRequestDispatcher("admin/menu-list.jsp");
			rd.forward(request, response);
		} else {
			RequestDispatcher rd = request
					.getRequestDispatcher("admin/admin-login.html");
			rd.forward(request, response);
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession().getAttribute("ADMIN_USERNAME") != null) {
			String action = request.getParameter("action");
			if (action.equals("edit")) {
				int id = Integer.parseInt(request.getParameter("id"));
				MenuDAO menuDao = new MenuDAO();
				MenuDTO menu = new MenuDTO();
				menu.setId(id);
				menuDao.get(menu);

				DietDAO dietDAO = new DietDAO();
				ArrayList<DietDTO> list = dietDAO.select();

				request.setAttribute("DIETLIST", list);
				request.setAttribute("MENUDTO", menu);
				RequestDispatcher rd = request
						.getRequestDispatcher("admin/menu-edit.jsp");
				rd.forward(request, response);
			}
		} else {
			RequestDispatcher rd = request
					.getRequestDispatcher("admin/admin-login.html");
			rd.forward(request, response);
		}

	}
}
